/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.jm.financeiro.datamodel;

import br.jm.financeiro.entity.Moeda;
import br.jm.financeiro.sistema.eao.MoedaEao;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

/**
 *
 * @author joao
 */
public class LazyMoeda extends LazyDataModel<Moeda> {

    private List<Moeda> datasource;
    private final MoedaEao moedaJpa;
    private String cFiltro;
    private String cParametroSQL;
    private boolean lSorter;
    private final int dataSize;

    public LazyMoeda(MoedaEao moedaJpa) {
        this.moedaJpa = moedaJpa;
        this.dataSize = moedaJpa.getCount("Moeda");
    }

    @Override
    public Moeda getRowData(String rowKey) {
        for (Moeda moeda : datasource) {
            if (moeda.getNomMoeda().equals(rowKey)) {
                return moeda;
            }
        }

        return null;
    }

    @Override
    public Object getRowKey(Moeda moeda) {
        return moeda.getId();
    }

    @Override
    public void setRowIndex(int rowIndex) {
        /*
         * The following is in ancestor (LazyDataModel):
         * this.rowIndex = rowIndex == -1 ? rowIndex : (rowIndex % pageSize);
         */
        if (rowIndex == -1 || getPageSize() == 0) {
            super.setRowIndex(-1);
        } else {
            super.setRowIndex(rowIndex % getPageSize());
        }
    }
    
    @Override
    public List<Moeda> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
        List<Moeda> data = new ArrayList<>();
        try {
            //filter
            lSorter = SortOrder.ASCENDING.equals(sortOrder);

            data = moedaJpa.getNative("Moeda", first, pageSize, sortField, lSorter, filters, cParametroSQL, cFiltro);
        } catch (Exception ex) {
            //Logger.getLogger(LazyMoeda.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        this.setRowCount(dataSize);
        if (filters.isEmpty()) {
            if (data.isEmpty()) {
                this.setRowCount(0);
            } else {
                this.setRowCount(this.dataSize);
            }
        }
        
        return data;
    }
}
